#include <string.h>
#include "iec101.h"

time_t get_cp24time2a(const cp24time2a_t *cp24) {
	time_t t;
	struct tm tp;

	time(&t);
	localtime_r(&t, &tp);

	tp.tm_sec = cp24->msec / 1000;
	tp.tm_min = cp24->min;

	return mktime(&tp);
}

time_t get_cp32time2a(const cp32time2a_t *cp32) {
	time_t t;
	struct tm tp;

	time(&t);
	localtime_r(&t, &tp);

	tp.tm_sec = cp32->msec / 1000;
	tp.tm_min = cp32->min;
	tp.tm_hour = cp32->hour;

	return mktime(&tp);
}

time_t get_cp56time2a(const cp56time2a_t *cp56) {
	struct tm tp;

	bzero(&tp, sizeof(struct tm));

	tp.tm_sec = cp56->msec / 1000;
	tp.tm_min = cp56->min;
	tp.tm_hour = cp56->hour;
	tp.tm_mday = cp56->day;
	tp.tm_mon = cp56->mon - 1;
	tp.tm_year = cp56->year + 2000;

	return mktime(&tp);
}

void set_cp56time2a(cp56time2a_t *cp56, const time_t t) {
	struct tm tp;
	localtime_r(&t, &tp);

	bzero(cp56, sizeof(cp56time2a_t));

	cp56->msec = (uint16_t) (tp.tm_sec * 1000);
	cp56->min = (uint8_t) tp.tm_min;
	cp56->hour = (uint8_t) tp.tm_hour;
	cp56->day = (uint8_t) tp.tm_mday;
	cp56->mon = (uint8_t) (tp.tm_mon + 1);
	cp56->year = (uint8_t) (tp.tm_year % 100);
}